package com.github.liaochong.example.controller;

import com.github.liaochong.example.pojo.Product;
import com.github.liaochong.myexcel.core.BeetlExcelBuilder;
import com.github.liaochong.myexcel.core.ExcelBuilder;
import com.github.liaochong.myexcel.core.WorkbookType;
import com.github.liaochong.myexcel.core.strategy.WidthStrategy;
import com.github.liaochong.myexcel.utils.AttachmentExportUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author liaochong
 * @version 1.0
 */
@Controller
public class CustomerBeetlExcelBuilderExampleController {

    /**
     * use non-default-style excel builder
     *
     * @param response response
     */
    @GetMapping("/custom/example")
    public void build(HttpServletResponse response) throws IOException {
        try (ExcelBuilder excelBuilder = new BeetlExcelBuilder().widthStrategy(WidthStrategy.CUSTOM_WIDTH)) {
            Map<String, Object> dataMap = this.getDataMap();

            Workbook workbook = excelBuilder.template("/templates/报表/广东省内与地市结算/2019年xx月移动支付技术平台技术服务费成本清分汇总表.btl").build(dataMap);
            AttachmentExportUtil.export(workbook, "beetl_excel", response);
        }
    }


    private Map<String, Object> getDataMap() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("sheetName", "shee1");
        dataMap.put("month", "11");
        dataMap.put("date", "20191128");
        dataMap.put("tel", "18960863890");
        dataMap.put("makename", "498报表系统");


        List<Map<String, Object>> data = new ArrayList<>();
        dataMap.put("data", data);
        for (int i = 0; i < 10; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", "潮州");
            BigDecimal trademoney = i % 2 == 0 ? random() : BigDecimal.ZERO;
            item.put("tradeMoney", trademoney);
            item.put("serviceCharge", trademoney.multiply(BigDecimal.valueOf(0.035 * 0.01)).setScale(2,BigDecimal.ROUND_HALF_UP));
            data.add(item);

        }
        // 合计
        Map<String, Object> sumMap = new HashMap<>();
        data.add(sumMap);
        sumMap.put("name", "合计");
        sumMap.put("tradeMoney", sum(3, data.size() + 1, "B"));
        sumMap.put("serviceCharge", sum(3, data.size() + 1, "C"));
        return dataMap;
    }

    private String sum(int begin, int end, String column) {
        return "SUM(" + column + begin + ":" + column + end + ")";
    }

    public BigDecimal random() {
        float min = 1f;
        float max = 1000f;
        float floatBounded = min + new Random().nextFloat() * (max - min);
        return BigDecimal.valueOf(floatBounded).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}
